#import "ZLLabel.h"
#import "ZLTextLayout.h"

@interface ZLLabel ()

@property (nonatomic, strong) ZLTextLayout *textLayout;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) BOOL needsUpdateLayout;

@end

@implementation ZLLabel

#pragma mark - Initialization

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.backgroundColor = [UIColor clearColor];
    self.userInteractionEnabled = YES;
    _numberOfLines = 0;
    _textAlignment = NSTextAlignmentLeft;
    
    // 移除现有的手势识别器
    for (UIGestureRecognizer *gesture in self.gestureRecognizers) {
        [self removeGestureRecognizer:gesture];
    }
    
    // 添加触摸手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    tapGesture.cancelsTouchesInView = NO;
    [self addGestureRecognizer:tapGesture];
}

#pragma mark - Override Methods

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (self.needsUpdateLayout) {
        [self updateTextLayout];
    }
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    if (!self.textLayout) return;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (!context) return;
    
    CGContextSaveGState(context);
    [self.textLayout drawInContext:context];
    CGContextRestoreGState(context);
}

#pragma mark - Public Methods

- (void)setAttributedText:(NSAttributedString *)attributedText {
    if (_attributedText != attributedText) {
        _attributedText = [attributedText copy];
        [self updateTextLayoutIfNeeded];
    }
}

- (void)setNumberOfLines:(NSInteger)numberOfLines {
    if (_numberOfLines != numberOfLines) {
        _numberOfLines = numberOfLines;
        [self updateTextLayoutIfNeeded];
    }
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment {
    if (_textAlignment != textAlignment) {
        _textAlignment = textAlignment;
        [self updateTextLayoutIfNeeded];
    }
}

- (void)addHighlight:(ZLTextHighlight *)highlight {
    if (!highlight) return;
    
    NSLog(@"添加高亮文本，范围: %@", NSStringFromRange(highlight.range));
    [self.textLayout addHighlight:highlight];
    [self setNeedsDisplay];
}

- (void)addLinkForText:(NSString *)text withAction:(void(^)(void))action {
    if (!text || text.length == 0 || !self.attributedText) {
        NSLog(@"添加链接文本失败：参数无效");
        return;
    }
    
    NSString *string = self.attributedText.string;
    NSRange searchRange = NSMakeRange(0, string.length);
    NSRange foundRange;
    
    NSLog(@"开始查找文本：%@", text);
    
    while ((foundRange = [string rangeOfString:text options:0 range:searchRange]).location != NSNotFound) {
        NSLog(@"找到匹配文本，范围：%@", NSStringFromRange(foundRange));
        
        ZLTextHighlight *highlight = [ZLTextHighlight highlightWithRange:foundRange];
        highlight.tapAction = [action copy]; // 确保 block 被复制
        highlight.normalColor = [UIColor systemBlueColor];
        highlight.highlightColor = [UIColor colorWithRed:0.0 green:0.478 blue:1.0 alpha:0.5];
        highlight.showUnderline = YES;
        
        [self addHighlight:highlight];
        
        // 更新搜索范围
        searchRange.location = foundRange.location + foundRange.length;
        searchRange.length = string.length - searchRange.location;
    }
}

- (void)removeAllHighlights {
    [self.textLayout removeAllHighlights];
    [self setNeedsDisplay];
}

#pragma mark - Private Methods

- (void)updateTextLayoutIfNeeded {
    self.needsUpdateLayout = YES;
    [self setNeedsLayout];
}

- (void)updateTextLayout {
    if (!self.attributedText) return;
    
    // 创建新的文本布局
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    // 添加文本对齐属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = self.textAlignment;
    [text addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
    
    // 更新文本布局
    self.textLayout = [[ZLTextLayout alloc] initWithText:text size:self.bounds.size];
    self.needsUpdateLayout = NO;
    
    [self setNeedsDisplay];
}

- (void)handleTap:(UITapGestureRecognizer *)gesture {
    NSLog(@"点击事件触发");
    
    if (gesture.state == UIGestureRecognizerStateEnded) {
        // 获取点击位置相对于视图的坐标
        CGPoint point = [gesture locationInView:self];
        NSLog(@"原始点击位置: %@", NSStringFromCGPoint(point));
        
        // 确保文本布局已更新
        if (self.needsUpdateLayout) {
            [self updateTextLayout];
        }
        
        // 检查是否有高亮文本
        if (self.textLayout.highlights.count > 0) {
            NSLog(@"当前高亮数量: %lu", (unsigned long)self.textLayout.highlights.count);
            
            // 打印所有高亮文本的信息
            for (ZLTextHighlight *highlight in self.textLayout.highlights) {
                NSString *highlightText = [self.attributedText.string substringWithRange:highlight.range];
                NSLog(@"高亮文本: %@, 范围: %@, 回调: %@",
                      highlightText,
                      NSStringFromRange(highlight.range),
                      highlight.tapAction ? @"存在" : @"不存在");
                
                // 获取高亮文本的边界框
                NSRange glyphRange = [self.textLayout.layoutManager glyphRangeForCharacterRange:highlight.range
                                                                       actualCharacterRange:NULL];
                CGRect boundingRect = [self.textLayout.layoutManager boundingRectForGlyphRange:glyphRange
                                                                           inTextContainer:self.textLayout.textContainer];
                NSLog(@"高亮文本边界框: %@", NSStringFromCGRect(boundingRect));
                
                // 检查点击位置是否在边界框内
                if (CGRectContainsPoint(boundingRect, point)) {
                    NSLog(@"点击位置在高亮文本边界框内");
                    if (highlight.tapAction) {
                        NSLog(@"执行点击回调");
                        dispatch_async(dispatch_get_main_queue(), ^{
                            highlight.tapAction();
                        });
                    }
                    return;
                }
            }
            
            NSLog(@"点击位置不在任何高亮文本边界框内");
        } else {
            NSLog(@"没有高亮文本");
        }
    }
}

@end 
